package com.biz.primus.ms.homepage.helper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;

import static com.google.common.collect.Maps.newHashMap;
import static java.lang.String.format;

/**
 * Created by defei on 2/10/17.
 */
public class BeanDiscoverer {

    public static void put(MethodExecutable bean) {
        if (bean== null){
            throw new RuntimeException("Argument bean is blank.");
        }
        if (StringUtils.isBlank(bean.getIdentity())){
            throw new IllegalArgumentException("Argument key is blank.");
        }
        if (keyToBean.containsKey(bean.getIdentity())) {
            logger.warn("Bean:[{}] for key:[{}] is duplicate.", bean.getClass(), bean.getIdentity());
            throw new RuntimeException(format("Bean:[%s] for key:[%s] is duplicate.", bean.getClass(), bean.getIdentity()));
        }
        keyToBean.put(bean.getIdentity(), bean);
    }

    public static MethodExecutable getBean(String key) {

        MethodExecutable bean = keyToBean.get(key);
        if (bean == null) {
            logger.warn("Bean not found for key:[{}].", key);
        }
        return bean;
    }

    public static Collection<MethodExecutable> getCoverTemplateElementDataProviders(){

        return keyToBean.values();
    }

    private static final Map<String, MethodExecutable> keyToBean = newHashMap();

    private static final Logger logger = LoggerFactory.getLogger(BeanDiscoverer.class);
}
